package org.ziegler.db.loadAndSave;

import java.util.Objects;

/**
 * 任务对象
 * @author Ziegler
 * date : 2020/7/25 16:11
 */
public class Quest {

    private final QuestManager questManager;

    private final int questSn;

    private QuestStateType questStateType;

    public Quest(int questSn, QuestStateType questStateType, QuestManager questManager) {
        this.questSn = questSn;
        this.questStateType = Objects.requireNonNull(questStateType);
        this.questManager = Objects.requireNonNull(questManager);
    }

    void init() {
        System.out.println("Quest.init questSn = " + questSn + ", questStateType = " + questStateType);

        if (questStateType == QuestStateType.PREPARE) {
            questManager.getQuestDB().setQuestStateIndex(QuestStateType.SUBMITTED);
            changeState(QuestStateType.SUBMITTED);
        }

        if (questStateType == QuestStateType.REWARD) {
            changeState(QuestStateType.FINISH);
        }
    }

    public void submit() {
        if (questStateType == QuestStateType.SUBMITTED) {
            System.out.println("Quest.submit");

            questManager.getQuestDB().setQuestStateIndex(QuestStateType.REWARD);
            changeState(QuestStateType.REWARD);
        }
    }

    public void giveUp() {
        System.out.println("Quest.giveUp");

        // 这里的数据库保存可以不处理，因为finish阶段会重置
        questManager.getQuestDB().setQuestStateIndex(QuestStateType.FINISH);
        changeState(QuestStateType.FINISH);
    }

    private void reward() {
        System.out.println("Quest.reward");

        // 这里的数据库保存可以不处理，因为finish阶段会重置
        questManager.getQuestDB().setQuestStateIndex(QuestStateType.FINISH);
        changeState(QuestStateType.FINISH);
    }

    private void finish() {
        System.out.println("Quest.finish");

        questManager.getQuestDB().setQuestSn(0);
        questManager.getQuestDB().setQuestStateIndex(QuestStateType.PREPARE);

        changeState(QuestStateType.DESTROY);
    }

    private void changeState(QuestStateType questStateType) {
        if (this.questStateType == questStateType) {
            return ;
        }

        this.questStateType = questStateType;

        if (questStateType == QuestStateType.REWARD) {
            reward();
        } else if (questStateType == QuestStateType.FINISH) {
            finish();
        }
    }

    boolean isDestroy() {
        return questStateType == QuestStateType.DESTROY;
    }

}
